<template>
  <div class="learning-container">
    <Header></Header>
    <Cover title="学习管理" subtitle="丰富的学习资料，更好的学习体验" img="banner.png"></Cover>
    
    <div class="page-content">
      <!-- 顶部操作栏 -->
      <div class="top-actions">
        <el-button type="primary" @click="showAddDialog = true">
          <i class="el-icon-plus"></i> 添加学习资料
        </el-button>
        <div class="search-box">
          <el-input
            v-model="keyword"
            placeholder="搜索学习资料..."
            prefix-icon="el-icon-search"
            @input="handleSearch"
          >
          </el-input>
        </div>
      </div>

      <!-- 资料分类标签 -->
      <div class="category-tabs">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="全部资料" :name="'all'"></el-tab-pane>
          <el-tab-pane label="内部资源" :name="0"></el-tab-pane>
          <el-tab-pane label="外部资源" :name="1"></el-tab-pane>
          <!-- <el-tab-pane label="我的收藏" name="collect"></el-tab-pane> -->
          <el-tab-pane label="我的上传" name="my"></el-tab-pane>
        </el-tabs>
      </div>

      <!-- 资料列表 -->
      <div class="learning-list">
        <el-row :gutter="20">
          <el-col :span="8" v-for="item in learningList" :key="item.id">
            <el-card class="learning-card" shadow="hover">
              <div class="learning-cover">
                <img :src="item.image || 'default-cover.png'" :alt="item.title">
                <div class="learning-type" :class="item.type === 0 ? 'internal' : 'external'">
                  {{ item.type === 0 ? '内部资源' : '外部资源' }}
                </div>
              </div>
              <div class="learning-info">
                <h3 class="title">{{ item.title }}</h3>
                <p class="description">{{ item.description }}</p>
                <div class="meta">
                  <span class="size" v-if="item.fileSize">
                    <i class="el-icon-document"></i>
                    {{ formatFileSize(item.fileSize) }}
                  </span>
                  <span class="type">
                    <i class="el-icon-folder"></i>
                    {{ item.fileType === 0 ? '网络资源' : '用户投稿' }}
                  </span>
                </div>
                <div class="actions">
                  <!-- 网络资源显示学习按钮 -->
                  <template v-if="item.fileType === 0">
                    <el-button type="text" @click="handleLearn(item)">
                      <i class="el-icon-reading"></i> 学习
                    </el-button>
                  </template>
                  <!-- 本地资源显示预览和下载按钮 -->
                  <template v-else>
                    <el-button type="text" @click="previewLearning(item)">
                      <i class="el-icon-view"></i> 预览
                    </el-button>
                    <el-button type="text" @click="downloadLearning(item)">
                      <i class="el-icon-download"></i> 下载
                    </el-button>
                  </template>
                  <!-- 通用的点赞和收藏按钮 -->
                  <el-button 
                    type="text" 
                    @click="handleLike(item)"
                    :class="{ 'is-liked': item.isLiked }"
                  >
                    <i :class="item.isLiked ? 'el-icon-star-on' : 'el-icon-star-off'"></i>
                    {{ item.likes || 0 }}
                  </el-button>
                  <el-button 
                    type="text" 
                    @click="handleCollect(item)"
                    :class="{ 'is-collected': item.isCollected }"
                  >
                    <i :class="item.isCollected ? 'el-icon-collection' : 'el-icon-collection-tag'"></i>
                    收藏
                  </el-button>
                  <!-- 在"我的上传"标签页中显示修改和删除按钮 -->
                  <template v-if="activeTab === 'my'">
                    <el-button type="text" @click="handleEdit(item)">
                      <i class="el-icon-edit"></i> 修改
                    </el-button>
                    <el-button type="text" @click="handleDelete(item)">
                      <i class="el-icon-delete"></i> 删除
                    </el-button>
                  </template>
                </div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 分页器 -->
      <div class="pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageNo"
          :page-sizes="[5, 10, 20, 50]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>

    <!-- 添加资料对话框 -->
    <el-dialog
      title="添加学习资料"
      :visible.sync="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="learningForm" :rules="rules" ref="learningForm" label-width="100px">
        <el-form-item label="资料标题" prop="title">
          <el-input v-model="learningForm.title" placeholder="请输入资料标题"></el-input>
        </el-form-item>
        
        <el-form-item label="资料描述" prop="description">
          <el-input
            type="textarea"
            v-model="learningForm.description"
            :rows="3"
            placeholder="请输入资料描述"
          ></el-input>
        </el-form-item>

        <el-form-item label="资料分类" prop="channelId">
          <el-select v-model="learningForm.channelId" placeholder="请选择资料分类">
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资源类型" prop="type">
          <el-radio-group v-model="learningForm.type">
            <el-radio :label="0">内部资源</el-radio>
            <el-radio :label="1">外部资源</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文件类型" prop="fileType">
          <el-radio-group v-model="learningForm.fileType">
            <el-radio :label="0">网络资源</el-radio>
            <el-radio :label="1">本地上传</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="资源地址" prop="url" v-if="learningForm.fileType === 0">
          <el-input v-model="learningForm.url" placeholder="请输入资源URL地址"></el-input>
        </el-form-item>

        <el-form-item label="上传文件" prop="file" v-else>
          <el-upload
            class="upload-demo"
            action="http://121.37.242.119:20000/pss/images/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持任意格式文件，大小不超过100MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="http://121.37.242.119:20000/pss/images/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="learningForm.image" :src="learningForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showAddDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitForm('learningForm')">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 修改资料对话框 -->
    <el-dialog
      title="修改学习资料"
      :visible.sync="showEditDialog"
      width="600px"
      @close="resetEditForm"
    >
      <el-form :model="editForm" :rules="rules" ref="editForm" label-width="100px">
        <el-form-item label="资料标题" prop="title">
          <el-input v-model="editForm.title" placeholder="请输入资料标题"></el-input>
        </el-form-item>
        
        <el-form-item label="资料描述" prop="description">
          <el-input
            type="textarea"
            v-model="editForm.description"
            :rows="3"
            placeholder="请输入资料描述"
          ></el-input>
        </el-form-item>

        <el-form-item label="资料分类" prop="channelId">
          <el-select v-model="editForm.channelId" placeholder="请选择资料分类">
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资源类型" prop="type">
          <el-radio-group v-model="editForm.type">
            <el-radio :label="0">内部资源</el-radio>
            <el-radio :label="1">外部资源</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="文件类型" prop="fileType">
          <el-radio-group v-model="editForm.fileType">
            <el-radio :label="0">网络资源</el-radio>
            <el-radio :label="1">本地上传</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="资源地址" prop="url" v-if="editForm.fileType === 0">
          <el-input v-model="editForm.url" placeholder="请输入资源URL地址"></el-input>
        </el-form-item>

        <el-form-item label="上传文件" prop="file" v-else>
          <el-upload
            class="upload-demo"
            action="http://121.37.242.119:20000/pss/images/upload"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">支持任意格式文件，大小不超过100MB</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="封面图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="http://121.37.242.119:20000/pss/images/upload"
            :show-file-list="false"
            :on-success="handleEditAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="editForm.image" :src="editForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="showEditDialog = false">取 消</el-button>
        <el-button type="primary" @click="submitEditForm('editForm')">确 定</el-button>
      </div>
    </el-dialog>
    <Footer></Footer>
    <pdf-preview
      :visible.sync="showPdfPreview"
      :file-url="currentPdfUrl"
    ></pdf-preview>
  </div>

</template>

<script>
import axios from '../config/http';

export default {
  name: 'Learning',
  components: {
    Header: () => import("@/components/Header.vue"),
    Cover: () => import('@/components/Cover.vue'),
    Footer: () => import("@/components/Footer.vue"),
    PdfPreview: () => import("@/components/PdfPreview.vue")
  },
  data() {
    return {
      // 查询参数
      activeTab: 'all',    // 当前激活的标签页，默认显示全部资料
      type: 1,            // 资源类型：0内部，1外部
      keyword: '',         // 搜索关键字
      pageNo: 1,          // 页码
      pageSize: 5,        // 每页大小
      sortBy: 'id',       // 排序字段
      isAsc: true,        // 是否升序
      showPdfPreview: false,
      currentPdfUrl: '',
      total: 0,

      // 资料列表
      learningList: [],

      // 添加资料对话框
      showAddDialog: false,
      learningForm: {
        title: '',
        description: '',
        channelId: '',
        type: 0,
        fileType: 0,
        url: '',
        image: '',
        fileSize: 0
      },

      // 表单验证规则
      rules: {
        title: [
          { required: true, message: '请输入资料标题', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入资料描述', trigger: 'blur' }
        ],
        channelId: [
          { required: true, message: '请选择资料分类', trigger: 'change' }
        ],
        url: [
          { required: true, message: '请输入资源URL地址', trigger: 'blur' }
        ]
      },

      // 分类选项
      channelOptions: [
        { value: 1, label: '前端开发' },
        { value: 2, label: '后端开发' },
        { value: 3, label: '移动开发' },
        { value: 4, label: '数据库' }
      ],

      // 修改表单
      showEditDialog: false,
      editForm: {
        id: '',
        title: '',
        description: '',
        channelId: '',
        type: 0,
        fileType: 0,
        url: '',
        image: '',
        fileSize: 0
      },
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    // 获取数据（根据不同标签页调用不同接口）
    async fetchData() {
      switch (this.activeTab) {
        case 'all':
          await this.fetchLearningList();
          break;
        case 'collect':
          await this.fetchCollectList();
          break;
        case 'my':
          await this.fetchMyList();
          break;
      }
    },

    // 获取学习资料列表
    async fetchLearningList() {
      try {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          keyword: this.keyword || undefined,
          type: this.type,
          sortBy: this.sortBy,
          isAsc: this.isAsc
        };
        const res = await axios.get('/ls/learning/page', { params });
        if (res.data.code === 200) {
          this.learningList = (res.data.data.data.list || []).map(item => ({
            ...item,
            isCollected: item.collectOrNot,
            isLiked: item.likeOrNot
          }));
          this.total = res.data.data.total || 0;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      } catch (error) {
        console.error('获取学习资料列表失败:', error);
        this.$message.error('获取学习资料列表失败');
      }
    },

    // 获取我的收藏列表
    async fetchCollectList() {
      try {
        const res = await axios.get('/ls/learning/collect/my');
        if (res.data.code === 200) {
          this.learningList = res.data.data.data.list.map(item => ({
            ...item,
            isCollected: true, // 我的收藏列表中的项目默认为已收藏
            isLiked: item.likeOrNot
          }));
          this.total = res.data.data.total;
        } else {
          this.$message.error(res.data.msg || '获取收藏列表失败');
        }
      } catch (error) {
        console.error('获取收藏列表失败:', error);
        this.$message.error('获取收藏列表失败');
      }
    },

    // 获取我的上传列表
    async fetchMyList() {
      try {
        const res = await axios.get('/ls/learning/my');
        if (res.data.code === 200) {
          // 处理返回的数据
          this.learningList = (res.data.data.data || []).map(item => ({
            ...item,
            isCollected: item.collectOrNot,
            isLiked: item.likeOrNot
          }));
          this.total = res.data.data.total || 0;
        } else {
          this.$message.error(res.data.msg || '获取上传列表失败');
        }
      } catch (error) {
        console.error('获取上传列表失败:', error);
        this.$message.error('获取上传列表失败');
      }
    },

    // 提交表单
    // async submitForm(formName) {
    //   this.$refs[formName].validate(async (valid) => {
    //     if (valid) {
    //       try {
    //         const res = await axios.post('/ls/learning/add', this.learningForm);
    //         if (res.data.code === 200) {
    //           this.$message.success('添加成功');
    //           this.showAddDialog = false;
    //           this.fetchData();
    //         } else {
    //           this.$message.error(res.data.msg || '添加失败');
    //         }
    //       } catch (error) {
    //         this.$message.error('添加失败');
    //       }
    //     }
    //   });
    // },
    async submitForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            // 如果是本地上传类型，检查是否已上传文件
            if (this.learningForm.fileType === 1 && !this.learningForm.url) {
              this.$message.error('请先上传文件');
              return;
            }

            console.log('提交的表单数据:', this.learningForm);
            const res = await axios.post('/ls/learning/add', this.learningForm);
            if (res.data.code === 200) {
              this.$message.success('添加成功');
              this.showAddDialog = false;
              this.fetchData();
            } else {
              this.$message.error(res.data.msg || '添加失败');
            }
          } catch (error) {
            console.error('添加失败:', error);
            this.$message.error('添加失败');
          }
        }
      });
    },
    // 重置表单
    resetForm() {
      this.$refs['learningForm'].resetFields();
      this.learningForm = {
        title: '',
        description: '',
        channelId: '',
        type: 0,
        fileType: 0,
        url: '',
        image: '',
        fileSize: 0
      };
    },

    // 文件上传相关方法
    handleUploadSuccess(response, file) {
  console.log('文件上传返回数据:', response);
  if (response.code === 200) {
    // response.data直接就是文件URL字符串
    if (this.showAddDialog) {
      this.learningForm.url = response.data;  // 直接使用返回的URL字符串
      this.learningForm.fileSize = file.size;
    } else if (this.showEditDialog) {
      this.editForm.url = response.data;  // 直接使用返回的URL字符串
      this.editForm.fileSize = file.size;
    }
    this.$message.success('文件上传成功');
  }
},

    handleUploadError() {
      this.$message.error('上传失败');
    },

    beforeUpload(file) {
      const isLt100M = file.size / 1024 / 1024 < 100;
      if (!isLt100M) {
        this.$message.error('上传文件大小不能超过 100MB!');
      }
      return isLt100M;
    },

    // 封面图片上传
    handleAvatarSuccess(response) {
      if (response.code === 200) {
        this.learningForm.image = response.data;  // 直接使用返回的url
        this.$message.success('上传成功');
      } else {
        this.$message.error(response.msg || '上传失败');
      }
    },

    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('上传封面图片只能是图片格式!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('上传封面图片大小不能超过 2MB!');
        return false;
      }
      return isImage && isLt2M;
    },

    // 分页方法
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchData();
    },

    handleCurrentChange(val) {
      this.pageNo = val;
      this.fetchData();
    },

    // 处理标签页切换
    async handleTabChange(tab) {
      this.pageNo = 1; // 切换标签页时重置页码
      
      if (tab.name === 'my') {
        await this.fetchMyList();
      } else if (tab.name === 'all') {
        this.type = 1; // 全部资料默认显示type=1
        await this.fetchLearningList();
      } else {
        this.type = parseInt(tab.name);
        await this.fetchLearningList();
      }
    },

    // 文件大小格式化
    formatFileSize(bytes) {
      if (bytes === 0) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },

    // 预览和下载方法
    previewLearning(item) {
  if (!item || !item.url) {
    this.$message.error('资源地址不存在');
    return;
  }

  try {
    // 获取文件扩展名
    const fileExt = item.url.split('.').pop().toLowerCase();
    
    // 图片类型直接预览
    const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
    if (imageExts.includes(fileExt)) {
      this.$message.success('正在打开图片预览');
      window.open(item.url, '_blank');
      return;
    }
    
    // PDF文件预览
    if (fileExt === 'pdf') {
      // 打开新窗口
      const previewWindow = window.open('', '_blank');
      
      // 使用更简单的字符串连接而不是嵌套模板字符串
      const pdfJsViewerUrl = 'https://mozilla.github.io/pdf.js/web/viewer.html?file=' + encodeURIComponent(item.url);
      
      // 设置预览窗口内容
      previewWindow.document.write([
        '<html>',
        '<head>',
        '<title>PDF预览</title>',
        '<style>',
        'body, html { margin: 0; padding: 0; height: 100%; overflow: hidden; }',
        'iframe { width: 100%; height: 100%; border: none; }',
        '</style>',
        '</head>',
        '<body>',
        '<iframe src="' + pdfJsViewerUrl + '" width="100%" height="100%"></iframe>',
        '</body>',
        '</html>'
      ].join(''));
      
      // 关闭文档流
      previewWindow.document.close();
      return;
    }
    
    // Office文档预览
    const officeExts = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
    if (officeExts.includes(fileExt)) {
      // 使用Microsoft Office Online预览服务
      const previewUrl = `https://view.officeapps.live.com/op/view.aspx?src=${encodeURIComponent(item.url)}`;
      this.$message.success('正在打开Office文档预览');
      window.open(previewUrl, '_blank');
      return;
    }
    
    // 文本文件直接预览
    const textExts = ['txt', 'json', 'xml', 'md', 'html', 'htm', 'css', 'js'];
    if (textExts.includes(fileExt)) {
      this.$message.success('正在打开文本预览');
      window.open(item.url, '_blank');
      return;
    }
    
    // 视频文件预览
    const videoExts = ['mp4', 'webm', 'ogg', 'mov'];
    if (videoExts.includes(fileExt)) {
      const videoWindow = window.open('', '_blank');
      videoWindow.document.write(`
        <html>
          <head>
            <title>视频预览</title>
            <style>
              body, html {
                margin: 0;
                padding: 0;
                height: 100%;
                background: #000;
                display: flex;
                justify-content: center;
                align-items: center;
              }
              video {
                max-width: 100%;
                max-height: 100%;
              }
            </style>
          </head>
          <body>
            <video controls autoplay>
              <source src="${item.url}" type="video/${fileExt}">
              您的浏览器不支持视频标签
            </video>
          </body>
        </html>
      `);
      return;
    }
    
    // 音频文件预览
    const audioExts = ['mp3', 'wav', 'ogg', 'flac'];
    if (audioExts.includes(fileExt)) {
      const audioWindow = window.open('', '_blank');
      audioWindow.document.write(`
        <html>
          <head>
            <title>音频预览</title>
            <style>
              body, html {
                margin: 0;
                padding: 0;
                height: 100vh;
                display: flex;
                justify-content: center;
                align-items: center;
                background: #f5f5f5;
              }
              audio {
                width: 80%;
              }
            </style>
          </head>
          <body>
            <audio controls autoplay>
              <source src="${item.url}" type="audio/${fileExt}">
              您的浏览器不支持音频标签
            </audio>
          </body>
        </html>
      `);
      return;
    }
    
    // 其他类型提示下载
    this.$message.info('该文件类型暂不支持预览，请下载后查看');
    this.downloadLearning(item);
  } catch (error) {
    console.error('预览文件失败:', error);
    this.$message.error('预览失败，请稍后重试');
  }
},

    downloadLearning(item) {
      try {
        // 创建一个隐藏的a标签
        const link = document.createElement('a');
        link.style.display = 'none';
        link.href = item.url;
        
        // 从URL中获取文件名
        const fileName = item.url.split('/').pop();
        link.download = fileName;
        
        // 添加到body中
        document.body.appendChild(link);
        
        // 触发点击
        link.click();
        
        // 移除元素
        document.body.removeChild(link);
        
        this.$message.success('开始下载文件');
      } catch (error) {
        console.error('下载文件失败:', error);
        this.$message.error('下载失败，请稍后重试');
        
        // 降级处理：直接打开URL
        window.location.href = item.url;
      }
    },

    // 处理学习按钮点击
    handleLearn(item) {
      window.open(item.url, '_blank');
    },

    // 处理点赞
    async handleLike(item) {
      try {
        const params = {
          learningId: item.id,
          operation: item.isLiked ? 0 : 1  // 1表示点赞，0表示取消点赞
        };
        
        const res = await axios.post('/ls/learning/like', params);
        if (res.data.code === 200) {
          item.isLiked = !item.isLiked;
          item.likes = item.isLiked ? (item.likes || 0) + 1 : (item.likes || 1) - 1;
          this.$message.success(item.isLiked ? '点赞成功' : '取消点赞成功');
        } else {
          this.$message.error(res.data.msg || '操作失败');
        }
      } catch (error) {
        console.error('点赞操作失败:', error);
        this.$message.error('操作失败，请稍后重试');
      }
    },

    // 处理收藏
    async handleCollect(item) {
      try {
        const params = {
          learningId: item.id,
          operation: item.isCollected ? 0 : 1  // 1表示收藏，0表示取消收藏
        };
        
        const res = await axios.post('/ls/learning/collect', params);
        if (res.data.code === 200) {
          item.isCollected = !item.isCollected;
          this.$message.success(item.isCollected ? '收藏成功' : '取消收藏成功');
        } else {
          this.$message.error(res.data.msg || '操作失败');
        }
      } catch (error) {
        console.error('收藏操作失败:', error);
        this.$message.error('操作失败，请稍后重试');
      }
    },

    // 处理搜索
    handleSearch() {
      this.pageNo = 1;
      this.fetchData();
    },

    // 处理排序变化
    handleSortChange() {
      this.fetchData();
    },

    // 处理排序方向变化
    handleOrderChange() {
      this.fetchData();
    },

    // 处理修改按钮点击
    handleEdit(item) {
      this.editForm = { ...item };
      this.showEditDialog = true;
    },

    // 处理删除按钮点击
    async handleDelete(item) {
      try {
        await this.$confirm('确认删除该学习资料吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const res = await axios.post(`/ls/learning/delete/${item.id}`);
        if (res.data.code === 200) {
          this.$message.success('删除成功');
          this.fetchMyList(); // 重新加载列表
        } else {
          this.$message.error(res.data.msg || '删除失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        }
      }
    },

    // 封面图片上传（修改表单）
    handleEditAvatarSuccess(response) {
      if (response.code === 200) {
        this.editForm.image = response.data;  // 直接使用返回的url
        this.$message.success('图片上传成功');
      } else {
        this.$message.error(response.msg || '图片上传失败');
      }
    },

    // 提交修改表单
    // async submitEditForm(formName) {
    //   this.$refs[formName].validate(async (valid) => {
    //     if (valid) {
    //       try {
    //         // 构建修改的参数
    //         const params = {
    //           ...this.editForm,
    //           image: this.editForm.image  // 确保图片URL被包含在请求中
    //         };
            
    //         const res = await axios.post('/ls/learning/update', params);
    //         if (res.data.code === 200) {
    //           this.$message.success('修改成功');
    //           this.showEditDialog = false;
    //           this.fetchMyList(); // 重新加载列表
    //         } else {
    //           this.$message.error(res.data.msg || '修改失败');
    //         }
    //       } catch (error) {
    //         console.error('修改失败:', error);
    //         this.$message.error('修改失败');
    //       }
    //     }
    //   });
    // },
    // 提交修改表单
    async submitEditForm(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            // 如果是本地上传类型，检查是否已上传文件
            if (this.editForm.fileType === 1 && !this.editForm.url) {
              this.$message.error('请先上传文件');
              return;
            }

            console.log('提交的修改表单数据:', this.editForm);
            const params = {
              ...this.editForm,
              image: this.editForm.image
            };
            
            const res = await axios.post('/ls/learning/update', params);
            if (res.data.code === 200) {
              this.$message.success('修改成功');
              this.showEditDialog = false;
              this.fetchMyList();
            } else {
              this.$message.error(res.data.msg || '修改失败');
            }
          } catch (error) {
            console.error('修改失败:', error);
            this.$message.error('修改失败');
          }
        }
      });
    },
    // 重置修改表单
    resetEditForm() {
      this.editForm = {
        id: '',
        title: '',
        description: '',
        channelId: '',
        type: 0,
        fileType: 0,
        url: '',
        image: '',
        fileSize: 0
      };
    },
  }
};
</script>

<style lang="less" scoped>
.learning-container {
  min-height: 100vh;
  background: #f5f7fa;

  .page-content {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;

    @media screen and (max-width: 768px) {
      padding: 10px;
    }
  }

  .top-actions {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;

    @media screen and (max-width: 768px) {
      flex-direction: column;
      gap: 10px;

      .search-box {
        width: 100%;
      }
    }

    .search-box {
      width: 300px;

      @media screen and (max-width: 1024px) {
        width: 250px;
      }
    }
  }

  .category-tabs {
    margin-bottom: 20px;
    background: #fff;
    padding: 0 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);

    @media screen and (max-width: 768px) {
      padding: 0 10px;
      :deep(.el-tabs__item) {
        padding: 0 10px;
      }
    }
  }

  .learning-list {
    margin-bottom: 20px;

    .el-row {
      @media screen and (max-width: 768px) {
        margin: 0 !important;
      }
    }

    .el-col {
      @media screen and (max-width: 768px) {
        width: 100%;
        padding: 0 !important;
      }

      @media screen and (min-width: 769px) and (max-width: 1024px) {
        width: 50%;
      }
    }

    .learning-card {
      margin-bottom: 20px;
      transition: all 0.3s;

      @media screen and (max-width: 768px) {
        margin-bottom: 15px;
      }

      &:hover {
        transform: translateY(-5px);

        @media screen and (max-width: 768px) {
          transform: translateY(-3px);
        }
      }

      .learning-cover {
        position: relative;
        height: 160px;
        overflow: hidden;

        @media screen and (max-width: 768px) {
          height: 140px;
        }

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .learning-type {
          position: absolute;
          top: 10px;
          right: 10px;
          padding: 2px 8px;
          border-radius: 12px;
          font-size: 12px;

          @media screen and (max-width: 768px) {
            font-size: 11px;
            padding: 1px 6px;
          }

          &.internal {
            background: #e1f3d8;
            color: #67c23a;
          }

          &.external {
            background: #fdf6ec;
            color: #e6a23c;
          }
        }
      }

      .learning-info {
        padding: 15px;

        @media screen and (max-width: 768px) {
          padding: 12px;
        }

        .title {
          margin: 0 0 10px;
          font-size: 16px;
          font-weight: bold;
          color: #303133;

          @media screen and (max-width: 768px) {
            font-size: 14px;
            margin: 0 0 8px;
          }
        }

        .description {
          margin: 0 0 10px;
          font-size: 14px;
          color: #606266;
          line-height: 1.4;
          height: 40px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;

          @media screen and (max-width: 768px) {
            font-size: 12px;
            height: 34px;
            margin: 0 0 8px;
          }
        }

        .meta {
          display: flex;
          justify-content: space-between;
          margin-bottom: 10px;
          font-size: 12px;
          color: #909399;

          @media screen and (max-width: 768px) {
            font-size: 11px;
            margin-bottom: 8px;
          }

          i {
            margin-right: 4px;
          }
        }

        .actions {
          display: flex;
          justify-content: flex-end;
          gap: 10px;

          @media screen and (max-width: 768px) {
            gap: 5px;
            flex-wrap: wrap;
          }

          .el-button {
            padding: 0 10px;

            @media screen and (max-width: 768px) {
              padding: 0 6px;
              font-size: 12px;
            }

            &.is-liked {
              color: #ff4d4f;
            }

            &.is-collected {
              color: #faad14;
            }
          }
        }
      }
    }
  }

  .pagination {
    text-align: center;
    margin-top: 30px;

    @media screen and (max-width: 768px) {
      margin-top: 20px;
      :deep(.el-pagination) {
        padding: 0;
        .el-pagination__sizes {
          display: none;
        }
      }
    }
  }
}

// 上传组件样式
.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;

    &:hover {
      border-color: #409EFF;
    }

    @media screen and (max-width: 768px) {
      width: 120px;
      height: 120px;
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;

  @media screen and (max-width: 768px) {
    width: 120px;
    height: 120px;
    line-height: 120px;
    font-size: 24px;
  }
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;

  @media screen and (max-width: 768px) {
    width: 120px;
    height: 120px;
  }
}
</style>